package com.broadsword.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;

public class LocalDateConverter implements Converter<LocalDate> {
    private static final List<DateTimeFormatter> FORMATTERS = Arrays.asList(DateTimeFormatter.ofPattern("yyyy-MM-dd"), DateTimeFormatter.ofPattern("yyyy/MM/dd"), DateTimeFormatter.ofPattern("yyyy年M月d日"));

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (CellDataTypeEnum.NUMBER.equals(cellData.getType()) && cellData.getNumberValue() != null) {
            //  easyExcel在解析时 该字段类型为Number. 值是从1900年1月1日到这一天的日期，所以添加解析器
            LocalDate localDate = LocalDate.of(1900, 1, 1);
            //execl的bug, 日期数差2
            return localDate.plusDays(cellData.getNumberValue().longValue()-2);
        }else if(CellDataTypeEnum.STRING.equals(cellData.getType()) && cellData.getStringValue() != null) {
            for (DateTimeFormatter formatter : FORMATTERS) {
                try {
                    return LocalDate.parse( cellData.getStringValue(), formatter);
                } catch (DateTimeParseException ignored) {
                }
            }
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }
}
